package org.juc.cp.badcall;

/**
 * 由于使用if进行判断，可能会产生虚假唤醒
 *
 * @author Admin
 * @date 2021/11/23F
 */
public class AirConditioner {
    // 资源类 资源
    private int number = 0;
    // 对外提供自增方法去进行操作资源类资源
    public synchronized void increment() throws InterruptedException {
        // 进来先判断资源是否已被生产出来 才决定是否继续生产
        if (number != 0) {
            wait();
        }
        //  干活
        number++;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //  通知
        notifyAll();
    }
    // 对外提供自减方法去进行操作资源类资源
    public synchronized void decrement() throws InterruptedException {
        // 进来先判断资源是否已有剩余资源能消费 才决定是否继续消费
        if (number == 0){
            wait();
        }
        // 通知
        number--;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        // 干活
        notifyAll();
    }

    public static void main(String[] args) {
        AirConditioner airConditioner = new AirConditioner();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
